package com.ikangtai.shecare.personal;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.DatePicker;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.BaseActivity;
import com.ikangtai.shecare.common.baseView.ListBar;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.eventBusMsg.MyInfo;
import com.ikangtai.shecare.common.eventBusMsg.UserInfo;
import com.ikangtai.shecare.common.util.ActivityCollector;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.AvatarImageMsg;
import com.ikangtai.shecare.common.util.DateUtil;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.ikangtai.shecare.common.util.SelfPermissionUtil;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

public class MyInfoActivity extends BaseActivity implements View.OnClickListener {

    private TopBar topBar;
    private ListBar nickName;
    private ListBar healthInfo;
    private ListBar dataReport;
    private ListBar birthday;
    private DatePickerDialog dialog;
    private int year, monthofYear, dayofMonth;
    private UserInfo userInfo = new UserInfo();
    private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    private static final int SET_AVATER_OK = 4;
    private static final int SET_AVATER_NOK = 5;
    private MyInfo myInfo = new MyInfo();
    private Bitmap bitmap;
    private static final String AVATAR_NAME = App.userName + "_avatar.jpg";
    private File tempFile;
    private DBManager dbManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_personal_my_info);
        ActivityCollector.addActivity(this);
        EventBus.getDefault().register(this);
        dbManager = new DBManager(this);
        initView();
    }

    private void initView() {
        topBar = (TopBar) findViewById(R.id.topBar);
        topBar.setOnTopBarClickListener(new TopBar.OnTopBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void midLeftClick() {

            }

            @Override
            public void midRightClick() {

            }

            @Override
            public void rightClick() {

            }
        });
        findViewById(R.id.avata).setOnClickListener(this);

        nickName = (ListBar) findViewById(R.id.nickName);
        nickName.setOnClickListener(this);

        healthInfo = (ListBar) findViewById(R.id.healthInfo);
        healthInfo.setOnClickListener(this);

        dataReport = (ListBar) findViewById(R.id.dataReport);
        dataReport.setOnClickListener(this);

        birthday = (ListBar) findViewById(R.id.birthday);
        birthday.setOnClickListener(this);

        String userBirthday = App.memory_preference_birthday;
        birthday.setRightText(userBirthday);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.nickName:
                Intent nickNameIntent = new Intent(this, NickNameActivity.class);
                startActivity(nickNameIntent);
                break;
            case R.id.healthInfo:
                Intent healthInfoIntent = new Intent(this, HealthInfoActivity.class);
                healthInfoIntent.putExtra("type", HealthInfoActivity.MYINFO_INTO);
                startActivity(healthInfoIntent);
                break;
            case R.id.dataReport:
                Intent dataReportIntent = new Intent(this, DataReportActivity.class);
                startActivity(dataReportIntent);
                break;
            case R.id.birthday:
                setDateDialog();
                break;
            case R.id.avata:
                chooseDialog();
                break;
        }
    }

    /**
     * 设置生日时间
     */
    private void setDateDialog() {
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        monthofYear = calendar.get(Calendar.MONTH);
        dayofMonth = calendar.get(Calendar.DAY_OF_MONTH);
        dialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String dete = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                if (DateUtil.isFutureDate(year + "/" + (monthOfYear + 1) + "/" + dayOfMonth)) {
                    Toast.makeText(MyInfoActivity.this, R.string.future_time, Toast.LENGTH_SHORT).show();
                } else {
                    birthday.setRightText(dete);
                    String setDete = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                    saveBirthday(setDete);
                }
            }
        }, year, monthofYear, dayofMonth);
        dialog.setCancelable(false);
        DatePicker datePicker = dialog.getDatePicker();
        datePicker.setMaxDate(new Date().getTime());
        dialog.show();
    }

    /**
     * sharepreference保存生日信息
     *
     * @param userBirthday
     */
    private void saveBirthday(String userBirthday) {
        AppLog.i("save birthday!");
        userInfo.setBirthday(userBirthday);
        EventBus.getDefault().post(userInfo);
        App.memory_preference_birthday = userBirthday;
        dbManager.updateUserPreference(App.userName, "birthday", userBirthday);
        uploadBirthday();
    }

    private void uploadBirthday() {

        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "user/registerUserInfo.json";
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("status", App.status);
            okHttpClient.add("birthday", App.memory_preference_birthday);
            okHttpClient.add("mensesLen", App.memory_preference_mensesLen);
            okHttpClient.add("periodLen", App.memory_preference_periodLen);
            okHttpClient.add("mensesType", App.memory_preference_mensesType);
            okHttpClient.add("lastPeriodDate", App.memory_preference_lastPeriodDate);

            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        String str = response.body().string();
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");

                        if (200 == respCode) {
                            AppLog.e("upload birthday success!");
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            uploadBirthday();
                        } else {
                        }
                    } catch (JSONException e) {
                        AppLog.i("upload registerUserInfo onResponse failed!");
                        e.printStackTrace();
                    }
                }
            });
        } catch (JSONException e) {
            AppLog.i("registerUserInfo exception!");
        }

    }

    /**
     * 拍照前，先判断是否有开启相机的权限，若没有则提示用户开启
     */
    private void chooseDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MyInfoActivity.this);
        // 指定下拉列表的显示数据
        final String[] cases = {getString(R.string.take_photo), getString(R.string.choose_photo)};
        // 设置一个下拉的列表选择项
        builder.setItems(cases, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        boolean hadCameraPermission = SelfPermissionUtil.checkCameraPermission(MyInfoActivity.this);
                        if (hadCameraPermission) { //有这个权限，做相应处理
                            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                            // 判断存储卡是否可以用，可用进行存储
                            if (hasSdcard()) {
                                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                        Uri.fromFile(new File(Environment
                                                .getExternalStorageDirectory(), AVATAR_NAME)));
                            }
                            startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
                        } else { //没有权限
                            Toast.makeText(MyInfoActivity.this, R.string.photo_permission, Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 1:
                        // 激活系统图库，选择一张图片
                        Intent intent1 = new Intent(Intent.ACTION_PICK);
                        intent1.setType("image/*");
                        startActivityForResult(intent1, PHOTO_REQUEST_GALLERY);
                        break;
                }
            }
        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                crop(uri);
            }

        } else if (requestCode == PHOTO_REQUEST_CAMERA) {
            if (hasSdcard()) {
                tempFile = new File(Environment.getExternalStorageDirectory(),
                        AVATAR_NAME);
                crop(Uri.fromFile(tempFile));
            } else {
                Toast.makeText(getApplicationContext(), R.string.no_photo_sd, Toast.LENGTH_SHORT).show();
            }

        } else if (requestCode == PHOTO_REQUEST_CUT) {
            try {

                bitmap = data.getParcelableExtra("data");
                sendImage(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 剪切
     *
     * @param uri
     */
    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        // 图片格式
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    private void sendImage(Bitmap bm) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] bytes = stream.toByteArray();
        String img = new String(Base64.encodeToString(bytes, Base64.DEFAULT));

        sendHttpPost(img, App.authToken);
        saveAvatarBitmap(bm);
    }

    /**
     * 保存图片
     *
     * @param bmp
     */
    private void saveAvatarBitmap(Bitmap bmp) {
        String externalCacheDir = this.getExternalCacheDir().getAbsolutePath() + "/";
        String avatarPath = externalCacheDir + AVATAR_NAME;

        File file = new File(avatarPath);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    private void sendHttpPost(final String imgBase64, String authToken) {
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "user/uploadHeadPhoto.json";
        try {
            okHttpClient.add("authToken", authToken);
            okHttpClient.add("img", imgBase64);
            okHttpClient.add("userName", App.userName);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {

                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");
                        if (App.HTTP_RESP_OK == respCode) {
                            myInfo.setRespCode(SET_AVATER_OK);
                            sendOKResp(myInfo);
                            AppLog.i("upload head photo onResponse success!");
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            sendHttpPost(imgBase64, App.authToken);
                        } else {
                            sendNOKResp();
                            AppLog.i("upload head photo onResponse respCode failed! is:" + respCode);
                        }
                    } catch (JSONException e) {
                        AppLog.i("upload head photo onResponse failed!");
                        sendNOKResp();
                        e.printStackTrace();
                    }
                }

                private void sendOKResp(MyInfo myInfo) {
                    EventBus.getDefault().post(myInfo);
                }

            });
        } catch (JSONException e) {
            sendNOKResp();
            e.printStackTrace();
        }
    }

    private void sendNOKResp() {
        MyInfo myInfo = new MyInfo(SET_AVATER_NOK);
        EventBus.getDefault().post(myInfo);
    }

    @Subcriber
    private void handleMyInfo(MyInfo myInfo) {
        switch (myInfo.getRespCode()) {
            case SET_AVATER_OK:
                AvatarImageMsg avatarImageMsg = new AvatarImageMsg();
                avatarImageMsg.setRespCode(2);
                EventBus.getDefault().post(avatarImageMsg);
                Toast.makeText(getApplicationContext(), R.string.portrait_success, Toast.LENGTH_SHORT).show();
                finish();
                break;
            case SET_AVATER_NOK:
                Toast.makeText(getApplicationContext(), R.string.portrait_fail, Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        ActivityCollector.removeActivity(this);
        super.onDestroy();
    }
}
